package com.baijiaoxi.common.utils.spring;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by shixj on 2017/9/7.
 */
public class FileDownUtil {
    private static HttpHeaders HttpHeadersFactory(String fileName) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(fileName.getBytes("gb2312"), "ISO8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return headers;
    }

    public static ResponseEntity downloadFile(FileSystemResource file, String fileName) throws IOException {
        return ResponseEntity
                .ok()
                .headers(HttpHeadersFactory(fileName))
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }


    public static ResponseEntity downloadFile(byte[] bfile, String fileName) throws IOException {
        InputStream inputStream = new ByteArrayInputStream(bfile);

        return ResponseEntity
                .ok()
                .headers(HttpHeadersFactory(fileName))
                .contentLength(bfile.length)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(inputStream)
                );
    }
}
